package com.yimi.yinhepda.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.pda.uce.commom.util.LogUtil;
import com.tencent.bugly.crashreport.CrashReport;
import com.webview.PadLogUtils;
import com.yimi.yinhepda.base.BaseApplication;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 000432
 */
public class CrashHandler implements UncaughtExceptionHandler {
    public static final String TAG = "CrashHandler";
    private static CrashHandler INSTANCE = new CrashHandler();
    private Context mContext;
    public static String sdPath;
    public static String errorLogPath;

    private List<Activity> mList = new LinkedList<Activity>();

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    public void init(Context ctx) {
        mContext = ctx;
        Thread.setDefaultUncaughtExceptionHandler(this);
        sdPath = Environment.getExternalStorageDirectory().getPath();
        if (TextUtils.isEmpty(sdPath)) {
            sdPath = Environment.getDataDirectory().getPath();
        }
        if (!TextUtils.isEmpty(sdPath)) {
            File file = new File(sdPath + "/Etong/");
            if (!file.exists()) {
                file.mkdir();
            }
            errorLogPath = sdPath + "/Etong/error/";
            File file1 = new File(errorLogPath);
            if (!file1.exists()) {
                file1.mkdir();
            }
        }
    }

    @Override
    public synchronized void uncaughtException(Thread thread, Throwable ex) {
        try {
            //把错误的堆栈信息 获取出来
            final String errorinfo = "YM错误信息" + getErrorInfo(ex);
            String timeStr = DateCommom.getTime("yyyy-MM-dd HH:mm:ss");
            if (errorLogPath != null) {
                DateCommom.appendTextToFile(errorLogPath + "error_log.txt",
                        "------收集错误时间" + timeStr + "------\r\n" + errorinfo + "\r\n" + "-----收集错误信息结束----\r\n\r\n");
            }
            LogUtil.e("崩溃信息\r\n+" + errorinfo);
            PadLogUtils.getInstance().loge("崩溃啦"+errorinfo);
            //上传BUGly
            CrashReport.postCatchedException(new RuntimeException(errorinfo));

            UploadErrorModule.getInstance().uploadData("1",errorinfo,mContext);

            //使用Toast来显示异常信息
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    ToastUtil.showToast("程序出现异常，即将退出");
                    Looper.loop();
                }
            }.start();
            Thread.sleep(3000);
            BaseApplication.getInstance().exit();
        } catch (Exception e) {
            e.printStackTrace();
            BaseApplication.getInstance().exit();
        }
    }

    /**
     * 获取错误的信息
     */
    @SuppressWarnings("unused")
    private String getErrorInfo(Throwable arg1) {
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        arg1.printStackTrace(pw);
        pw.close();
        String error = writer.toString();
        return error;
    }

//    public boolean isEmulator() {
//        TelephonyManager telephonemanage = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//        boolean isEmulator = "000000000000000".equalsIgnoreCase(telephonemanage.getDeviceId());
//        return isEmulator;
//    }

    // add Activity
    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    //关闭每一个list内的activity
    public void exit() {
        try {
            for (Activity activity : mList) {
                if (activity != null) activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}